<?php

namespace App\Http\Controllers\admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Article;
use App\Models\User;
use Auth;
use Intervention\Image\ImageManagerStatic as Image;

class ArticleController extends Controller
{
	// 显示文章
    public function index() {
        $u = User::find(Auth::id());
    	$article = new Article();
    	$articles = $article -> where('u_id', Auth::id()) -> paginate(10);
    	return view('admin.article',compact('articles','u'));
    }

    // 添加文章
    public function add(Request $request) {
        if($request -> isMethod('POST')) {
            $article = new Article;

            $data = $request -> only('title','content','keyword');

            $data['u_id'] = Auth::id();
            $path = 'uploads/'.date('Ymd').'/';
            $filename = md5(time()).'.'.$request->pic->extension();

            if($request -> hasFile('pic') && $request -> pic -> isValid()) {
                if($request -> pic -> move($path, $filename)) {
                    $path .= $filename;
                    $data['path'] = $path;
                    $article -> create($data);
                }
            }
            // 图片处理
            $image = Image::make($path)->resize(300, 200);
            $image -> save($path,80);
        }
        return view('admin.addarticle');
      
    }

    // 查看
    public function display($id) {
        $article = Article::find($id);
        $user = auth('admin')->user();
        return view('admin.articleinfo',compact('article','user'));
    }

    // 删除
    public function del($id) {
        $article = Article::find($id);
        if($article -> delete()) {
            return true;
        }else {
            return false;
        }
    }

    // 编辑
    public function edit(Request $request, $id) {
        $article = Article::find($id);
        if($request -> isMethod('POST')) {
            $data = $request->only('title','content','keyword');
            $path = 'uploads/'.date('Ymd').'/';
            $filename = md5(time()).'.'.$request->pic->extension();
            if($request -> hasFile('pic') && $request -> pic -> isValid()) {
                if($request -> pic -> move($path, $filename)) {
                    $path .= $filename;
                    $data['path'] = $path;
                }
            }
            if($article -> update($data)) {
                return redirect('/admin/article/index');
            }
        }
        return view('admin.editarticle',compact('article'));
    }
}
